<template>
    <el-dialog
        v-model="isShow"
        :align-center="true"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :title="formType === 'add' ? '添加用户' : '编辑用户'"
        class="dialog-box"
        @close="onCloseDialog"
    >
        <el-scrollbar max-height="450px">
            <el-form label-width="100" ref="formRef" :model="userForm" :rules="rules">
                <el-form-item prop="name" label="姓名">
                    <el-input v-model="userForm.name" placeholder="请输入姓名" clearable></el-input>
                </el-form-item>
                <el-form-item prop="userName" label="用户名">
                    <el-input v-model="userForm.userName" placeholder="请输入用户名" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-select v-model="userForm.roleIds" multiple clearable filterable collapse-tags collapse-tags-tooltip placeholder="请选择角色">
                        <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input
                        type="password"
                        show-password
                        v-model="userForm.password"
                        :placeholder="formType === 'add' ? '请输入密码' : '如果不修改密码请留空'"
                        clearable
                    ></el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword" label="确认密码">
                    <el-input
                        type="password"
                        show-password
                        v-model="userForm.confirmPassword"
                        :placeholder="formType === 'add' ? '请输入确认密码' : '如果不修改密码请留空'"
                        clearable
                    ></el-input>
                </el-form-item>
                <el-form-item prop="nickName" label="用户昵称">
                    <el-input v-model="userForm.nickName" placeholder="请输入用户昵称" clearable></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="userForm.email" placeholder="请输入邮箱" clearable></el-input>
                </el-form-item>
                <el-form-item prop="phoneNumber" label="电话号码">
                    <el-input v-model="userForm.phoneNumber" placeholder="请输入电话号码" clearable></el-input>
                </el-form-item>
                <el-form-item prop="description" label="描述">
                    <el-input type="textarea" v-model="userForm.description" placeholder="请输入描述"></el-input>
                </el-form-item>

                <div class="dialog-form-item-group">
                    <el-form-item prop="address" label="地址">
                        <el-cascader v-model="userForm.address" :options="regions" :props="regionsProps" clearable placeholder="请选择地址" />
                    </el-form-item>
                    <el-form-item prop="age" label="年龄">
                        <el-input-number v-model="userForm.age" :min="1" placeholder="请输入年龄" />
                    </el-form-item>
                    <el-form-item prop="gender" label="性别">
                        <el-radio-group v-model="userForm.gender">
                            <el-radio-button :value="1">男</el-radio-button>
                            <el-radio-button :value="2">女</el-radio-button>
                            <el-radio-button :value="3">其他</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </div>

                <el-form-item prop="avatar" label="头像">
                    <el-upload v-model="userForm.avatar" class="avatar-uploader" :http-request="onUploadRequest">
                        <el-image v-if="userForm.avatar" :src="userForm.avatar" />
                        <Icon v-else class="avatar-uploader-icon" name="el-Plus"></Icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="是否启用">
                    <el-switch v-model="userForm.isEnabled" />
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <el-button @click="onCancel">取消</el-button>
            <el-button @click="onConfirm" type="primary">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { RoleType } from '@/api/auth/role/types'
import { UserForm } from '@/api/auth/user/type'
import { FormInstance, FormRules, UploadRequestHandler, UploadRequestOptions } from 'element-plus'

const emit = defineEmits<{ onTableAction: [action: TableActionType, params: any] }>()
// 是否显示dialog
const isShow = ref(false)
// 表单类型
const formType = ref<FormType>('add')
// 表单实例 Ref
const formRef = ref<FormInstance>()
// 表单初始数据
const initform: Partial<UserForm> = {
    id: undefined,
    name: '',
    userName: '',
    password: '',
    confirmPassword: '',
    nickName: '',
    description: '',
    avatar: '',
    email: '',
    phoneNumber: '',
    address: [],
    gender: 1,
    age: 18,
    isEnabled: true,
    roleIds: [],
}
// 表单数据
const userForm = reactive<Partial<UserForm>>({ ...initform })
const roles = ref<RoleType[]>()
const regions = ref<any[]>()
const regionsProps = { label: 'name', value: 'name', children: 'children' }
watch(
    () => isShow.value,
    () => {
        if (isShow.value) {
            getRoles()
            getRegionsData()
        }
    },
)

const getRoles = async () => {
    const result = await getAllRoles()
    if (result.isSuccess) {
        roles.value = result.data
    }
}
const getRegionsData = async () => {
    const result = await getRegions()
    if (result.isSuccess) {
        regions.value = result.data
    }
}
// 表单校验规则
const rules = computed((): FormRules<UserForm> => {
    const addFormRules: FormRules<UserForm> = {
        userName: [
            {
                type: 'string',
                required: true,
                message: '用户名称不能为空',
                trigger: 'change',
            },
        ],
        password: [
            {
                required: true,
                message: '密码是必须的',
                trigger: 'change',
            },
            {
                min: 6,
                message: '密码不能小于6位',
                trigger: 'change',
            },
        ],
        confirmPassword: [
            {
                required: true,
                message: '请填写确认密码',
                trigger: 'change',
            },
            {
                validator(rule, value, callback, source) {
                    if (value.trim() !== userForm.password) {
                        callback('确认密码和密码不一致')
                    } else {
                        callback()
                    }
                },
                trigger: 'change',
            },
        ],
    }
    const editFormRules: FormRules<UserForm> = {
        userName: [
            {
                type: 'string',
                required: true,
                message: '用户名称不能为空',
                trigger: 'change',
            },
        ],
        password: [
            {
                min: 6,
                message: '密码不能小于6位',
                trigger: 'change',
            },
        ],
        confirmPassword: [
            {
                validator(rule, value, callback, source) {
                    if (value.trim() !== userForm.password) {
                        callback('确认密码和密码不一致')
                    } else {
                        callback()
                    }
                },
                trigger: ['blur', 'change'],
            },
        ],
    }
    return formType.value === 'add' ? addFormRules : editFormRules
})

const onUploadRequest = async (options: UploadRequestOptions): Promise<UploadRequestHandler | undefined> => {
    if (options.file.type !== 'image/jpeg' && options.file.type !== 'image/png' && options.file.type !== 'image/gif') {
        ElMessage.error('头像图片格式必须是 JPG | PNG | GIF ！')
        return
    } else if (options.file.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片大小不能超过2MB！')
        return
    }
    const result = await uploadFile(options.file)
    if (result.isSuccess) {
        userForm.avatar = result.data.url
    }
}
// 打开dialog
const onOpenDialog = (action: FormType, row?: UserForm) => {
    formType.value = action
    if (action !== 'add' && row) {
        Object.assign(userForm, row)
    }
    isShow.value = true
}
// 关闭dialog
const onCloseDialog = () => {
    isShow.value = false
    Object.assign(userForm, initform)
}
// 取消
const onCancel = () => onCloseDialog()
// 完成确认
const onConfirm = async () => {
    await formRef.value?.validate()

    emit('onTableAction', 'addOrEditSubmit', userForm)
}
defineExpose({
    onOpenDialog,
    onCloseDialog,
})
</script>

<style lang="scss" scoped>
.avatar-uploader {
    border: 1px dashed var(--el-border-color-lighter);

    &:hover {
        border: 1px dashed var(--el-color-primary);
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
}
.dialog-form-item-group {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
}
</style>
